package com.train.redis.core.utils;

import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Field;

public class KeyUtils {

    public static <T> String join(String format, T t) {
        Class<?> aClass = t.getClass();
        Class<?> superclass = aClass.getSuperclass();
        StringBuilder builder = buildKey(format, t, aClass);
        if (superclass != null) {
            builder = buildKey(builder.toString(), t, superclass);
        }
        return builder.toString();
    }

    private static <T> StringBuilder buildKey(String format, T t, Class<?> aClass) {
        Field[] declaredFields = aClass.getDeclaredFields();
        StringBuilder builder = new StringBuilder(format);
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            try {
                Object value = declaredField.get(t);
                if (value != null) {
                    if (value instanceof String) {
                        String columnValue = String.valueOf(value);
                        if (StrUtil.isEmpty(columnValue)) {
                            continue;
                        }
                    }
                    builder.append(":").append(value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return builder;
    }
}
